package require Tk

wm title . tkplay
grid [ttk::frame .info] -row 0 -sticky new
grid [ttk::frame .ctrl] -row 1 -sticky news
grid [ttk::label .info.name -text ...] -padx 1 -row 0 -sticky news
grid [ttk::scale .info.time -from 0 -command {
	apply {{name v} {
		upvar $name auplay
		auplay::seek auplay =$v
	}} auplay}] -row 1 -sticky news
grid [ttk::button .ctrl.prev -text << \
    -command {auplay::previous auplay}] -column 0 -row 0 -sticky news
grid [ttk::button .ctrl.rewind -text < \
    -command {auplay::seek auplay -10}] -column 1 -row 0 -sticky news
grid [ttk::button .ctrl.pause -text Pause \
    -command {auplay::pause auplay}] -column 2 -row 0 -sticky news
grid [ttk::button .ctrl.forward -text > \
    -command {auplay::seek auplay +10}] -column 3 -row 0 -sticky news
grid [ttk::button .ctrl.next -text >> \
    -command {auplay::next auplay}] -column 4 -row 0 -sticky news

grid columnconfigure . 0 -weight 1
grid rowconfigure . 0 -weight 0
grid rowconfigure . 1 -weight 1

grid columnconfigure .info 0 -weight 1
grid rowconfigure .info 0 -weight 1
grid rowconfigure .info 1 -weight 1

grid columnconfigure .ctrl 0 -weight 1
grid columnconfigure .ctrl 1 -weight 1
grid columnconfigure .ctrl 2 -weight 1
grid columnconfigure .ctrl 3 -weight 1
grid columnconfigure .ctrl 4 -weight 1
grid rowconfigure .ctrl 0 -weight 1

bind . <h> { auplay::previous auplay }
bind . <j> { auplay::previous auplay }
bind . <k> { auplay::next auplay }
bind . <l> { auplay::next auplay }
bind . <r> { auplay::restart auplay }
bind . <d> { auplay::delete auplay }
bind . <D> {
	auplay::delete auplay [file join [regsub -all {[][\\*?]} \
	    [file dirname $auplay(current)] {\\&}] *]
}
bind . <p> { auplay::pause auplay }
bind . <q> { auplay::destroy auplay }

bind .info.time <Configure> {
	if {[.info.time cget -to] == 0} { return }
	auplay::hz auplay [expr {max(int(
	    ceil([winfo width .info.time] / [.info.time cget -to])), 1
	)}]
}

auplay::create auplay -pi- {*}$argv

set auplay(oncurrent) {apply {{name item} {
	upvar $name auplay
	.info.name configure -text $auplay($item)
}}}

set auplay(ontime) {apply {{name item} {
	upvar $name auplay
	.info.time configure -value $auplay($item)
}}}

set auplay(onlength) {apply {{name item} {
	upvar $name auplay
	.info.time configure -to $auplay($item)
	if {$auplay($item) == 0} { return }
	auplay::hz auplay [expr {max(int(
	    ceil([winfo width .info.time] / $auplay($item))), 1
	)}]
}}}

set auplay(onpaused) {apply {{name item} {
	upvar $name auplay
	if {$auplay($item)} {
		.ctrl.pause configure -text Play
	} else {
		.ctrl.pause configure -text Pause
	}
}}}

wm protocol . WM_DELETE_WINDOW {
	auplay::destroy auplay
}
